﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Trul.Infrastructure.Crosscutting.Logging;

namespace Trul.WebUI.Infrastructure
{
    public class CustomHandleErrorAttribute : HandleErrorAttribute
    {
        public CustomHandleErrorAttribute()
            : base() {
            IsCustomView = false;
        }

        /// <summary>
        /// Default error sayfasina yonlendirme yapilmak istenmiyorsa true set edilir ve <see cref="View"/>'a yonlendirilmesi saglanir.
        /// </summary>
        public bool IsCustomView { get; set; }

        public override void OnException(ExceptionContext filterContext) {
            if(!ExceptionType.IsInstanceOfType(filterContext.Exception)) {
                return;
            }

            // if the request is AJAX return JSON else view.
            if(filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest") {
                filterContext.Result = new JsonResult {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = new {
                        error = true,
                        message = filterContext.Exception.Message
                    }
                };
            } else {

                HttpContext.Current.Application[HttpContext.Current.Request.UserHostAddress.ToString()] = filterContext.Exception;
                if(IsCustomView) {
                    var controllerName = (string)filterContext.RouteData.Values["controller"];
                    var actionName = (string)filterContext.RouteData.Values["action"];
                    var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
                    filterContext.Result = new ViewResult {
                        ViewName = View,
                        MasterName = Master,
                        ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                        TempData = filterContext.Controller.TempData
                    };
                } else {
                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(
                        new {
                            controller = "Error",
                            action = "HttpError"
                        }));
                }
            }

            LoggerFactory.CreateLog().LogError(filterContext.Exception.Message, filterContext.Exception);

            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 500;

            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }
    }
}